#-*- coding:UTF-8 -*-
import cgi
import os
import django
from django.http import *
from django import shortcuts
#from django.db import models

from google.appengine.ext.db import djangoforms

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
#from google.appengine.ext.webapp import template
import logging

from actions.baseaction import *
from actions.paginator import *


class Greeting(db.Model):
  author = db.UserProperty()
  title = db.StringProperty(verbose_name="标题",required=True)
  content = db.TextProperty(verbose_name="留言内容")
  email = db.EmailProperty(verbose_name="邮件地址")

  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)

class GreetingForm(djangoforms.ModelForm):
  class Meta:
    model = Greeting
    exclude = ['author', 'created', 'modified']


def edit(request, greet_id):
   user = users.GetCurrentUser()
   try:
	  
	  #在app.yaml里已经配置了login=required，这里不用再判断
	  #if user is None:
	    #print "user is null"
	    #return http.HttpResponseForbidden('您必须登陆才能编辑！')
	    #return http.HttpResponseRedirect('/notlogin')

	  greet = None
	  if greet_id:
	    greet = Greeting.get(db.Key.from_path(Greeting.kind(), int(greet_id)))
	    if greet is None:
	      return respond(request, user, 'notfound', {'redirecturl': '/guestbook/', 'error_message': '您正在编辑的信息不存在，ID 为 (%r)' % greet_id})
	      #http.HttpResponseNotFound('您正在编辑的信息不存在，ID 为 (%r)' % greet_id)

	  form = GreetingForm(data=request.POST or None, instance=greet)

	  if not request.POST:
		return respond(request, user, 'guestbook/guestbook', {'form': form, 'greeting': greet})

	  errors = form.errors
	  if not errors:
	    try:
	      greet = form.save(commit=False)
	    except ValueError, err:
	      errors['__all__'] = unicode(err)
	  if errors:
	    return respond(request, user, 'guestbook/guestbook', {'form': form, 'greeting': greet})

	  if not greet.author:
	    greet.author = user
	  greet.put()

	  return HttpResponseRedirect('/guestbook/')
   except Exception ,e:
      logging.error(e)
      return http.HttpResponseServerError("系统错误，请与管理员联系！")

def show(request):
   user = users.GetCurrentUser()
   try:
	  url = users.create_login_url('/')
	  url_linktext = 'Login'
	  offset = getParameter(request ,"offset")
	  if not offset :
	    offset=1
	  else:
	    offset = int(offset)
	  
	  if user:
	    greetings_q = db.GqlQuery("select * from Greeting where author=:1 order by created desc ",user) #limit 10
	    pager = Paginator(greetings_q,2)
	    try:
	      greetings = pager.page(offset)
	    except (EmptyPage, InvalidPage):
	      greetings = pager.page(pager.num_pages)
	  else:
	    greetings = {}
	  return respond(request, user, 'guestbook/listguestbook', {'greetings': greetings,'url': url,'url_linktext': url_linktext})
   except Exception ,e:
      logging.error(e)
      return http.HttpResponseServerError("系统错误，请与管理员联系！")

def new(request):
  return edit(request, None)


